<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cates;
use Illuminate\Http\Request;

class CateController extends Controller {

    public function index(Request $request){
        $pid = $request->get('pid');
        $lists = Cates::categories($pid);
        return $this->writeJson(0,$lists);
    }

    //列表所需的分类筛选
    public function all(Request $request){
        $pid = $request->get('pid',1000);
        $lists = Cates::where('pid',$pid)->get();
        return $this->writeJson(0,$lists);
    }

    public function update(Request $request)
    {
        $data = $request->all();
        $data['pid'] = (int)end($data['pitch']);
        $info = Cates::select(['pitch'])->where('id',$data['pid'])->first();
        if($info['pitch'] && is_array($info['pitch'])){
            $data['pitch'] = array_merge($info['pitch'],[(int)$data['pid']]);
        }else{
            $data['pitch'] = [$data['pid']];
        }
        if($data['id']){
            $info->update($data);
            return $this->writeJson(0,null,'编辑类目信息成功');
        }else{
            //新增
            unset($data['id']);
            Cates::create($data);
            return $this->writeJson(0,null,'新增类目信息成功');
        }
    }

    public function destroy(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }
        Cates::destroy($id);
        return $this->writeJson(0);
    }

}
